// 虚拟列表封装
import { useState, useEffect, useRef } from 'react'

interface VirtualListProps<T> {
  data: T[]
  itemHeight: number
  renderItem: (item: T, index: number) => React.ReactNode
  containerHeight: number
  className?: string
  onReachEnd?: () => void
  reachEndOffset?: number // 距离底部多少像素触发
}

const VirtualList = <T,>({
  data,
  itemHeight,
  renderItem,
  containerHeight,
  className = '',
  onReachEnd,
  reachEndOffset = 100,
}: VirtualListProps<T>) => {
  const containerRef = useRef<HTMLDivElement>(null)
  const [startIndex, setStartIndex] = useState(0)
  const [visibleCount, setVisibleCount] = useState(0)

  useEffect(() => {
    if (containerRef.current) {
      const count = Math.ceil(containerRef.current.clientHeight / itemHeight) + 2
      setVisibleCount(count)
    }
  }, [itemHeight, containerHeight])

  const handleScroll = () => {
    const el = containerRef.current
    if (!el) return

    const scrollTop = el.scrollTop
    const newStartIndex = Math.floor(scrollTop / itemHeight)
    setStartIndex(newStartIndex)

    // 触底检测
    if (onReachEnd) {
      const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - reachEndOffset
      if (nearBottom) onReachEnd()
    }
  }

  const endIndex = Math.min(startIndex + visibleCount, data.length)
  const visibleData = data.slice(startIndex, endIndex)

  const totalHeight = data.length * itemHeight
  const offsetY = startIndex * itemHeight

  return (
    <div
      ref={containerRef}
      className={`virtual-list ${className}`}
      style={{ height: `${containerHeight}px`, overflow: 'auto' }}
      onScroll={handleScroll}
    >
      <div
        className="virtual-list-container"
        style={{ height: `${totalHeight}px`, position: 'relative' }}
      >
        <div
          className="virtual-list-content"
          style={{ transform: `translateY(${offsetY}px)` }}
        >
          {visibleData.map((item, index) => (
            <div
              key={startIndex + index}
              style={{ height: `${itemHeight}px` }}
            >
              {renderItem(item, startIndex + index)}
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}

export default VirtualList